{% extends 'base.html' %}

{% block title %}Allen监控系统 - 首页{% endblock %}

{% block content %}
<div class="row">
    <!-- 设备统计卡片 -->
    <div class="col-md-6">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">设备统计</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="card bg-success text-white">
                            <div class="card-body">
                                <h5 class="card-title">可用主机</h5>
                                <h2 class="card-text">{{ host_count }}</h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card bg-danger text-white">
                            <div class="card-body">
                                <h5 class="card-title">停用主机</h5>
                                <h2 class="card-text">{{ disabled_count }}</h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card bg-info text-white">
                            <div class="card-body">
                                <h5 class="card-title">主机总数</h5>
                                <h2 class="card-text">{{ total_hosts }}</h2>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 告警统计卡片 -->
    <div class="col-md-6">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">告警统计</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3">
                        <div class="card bg-danger text-white">
                            <div class="card-body">
                                <h5 class="card-title">严重</h5>
                                <h2 class="card-text">{{ critical_alerts_count|default:"0" }}</h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-warning text-dark">
                            <div class="card-body">
                                <h5 class="card-title">紧急</h5>
                                <h2 class="card-text">{{ urgent_alerts_count|default:"0" }}</h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-primary text-white">
                            <div class="card-body">
                                <h5 class="card-title">警告</h5>
                                <h2 class="card-text">{{ warning_alerts_count }}</h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-secondary text-white">
                            <div class="card-body">
                                <h5 class="card-title">一般</h5>
                                <h2 class="card-text">{{ info_alerts_count }}</h2>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 资源占用TOP10 -->
<div class="card mt-4">
    <div class="card-header">
        <h5 class="mb-0">资源占用TOP10</h5>
    </div>
    <div class="card-body">
        <table class="table">
            <thead>
                <tr>
                    <th>主机名</th>
                    <th>IP地址</th>
                    <th width="20%">CPU使用率</th>
                    <th width="20%">内存使用率</th>
                    <th width="20%">磁盘使用率</th>
                </tr>
            </thead>
            <tbody>
                {% if top_resource_hosts %}
                    {% for host in top_resource_hosts %}
                    <tr>
                        <td>{{ host.hostname }}</td>
                        <td>{{ host.ip_address }}</td>
                        <td>
                            <div class="progress">
                                <div class="progress-bar {% if host.cpu_usage >= 90 %}bg-danger
                                    {% elif host.cpu_usage >= 70 %}bg-warning
                                    {% else %}bg-success{% endif %}"
                                    role="progressbar"
                                    style="width: {{ host.cpu_usage }}%"
                                    aria-valuenow="{{ host.cpu_usage }}"
                                    aria-valuemin="0"
                                    aria-valuemax="100">{{ host.cpu_usage }}%</div>
                            </div>
                        </td>
                        <td>
                            <div class="progress">
                                <div class="progress-bar {% if host.memory_usage >= 90 %}bg-danger
                                    {% elif host.memory_usage >= 70 %}bg-warning
                                    {% else %}bg-success{% endif %}"
                                    role="progressbar"
                                    style="width: {{ host.memory_usage }}%"
                                    aria-valuenow="{{ host.memory_usage }}"
                                    aria-valuemin="0"
                                    aria-valuemax="100">{{ host.memory_usage }}%</div>
                            </div>
                        </td>
                        <td>
                            <div class="progress">
                                <div class="progress-bar {% if host.disk_usage >= 90 %}bg-danger
                                    {% elif host.disk_usage >= 70 %}bg-warning
                                    {% else %}bg-success{% endif %}"
                                    role="progressbar"
                                    style="width: {{ host.disk_usage }}%"
                                    aria-valuenow="{{ host.disk_usage }}"
                                    aria-valuemin="0"
                                    aria-valuemax="100">{{ host.disk_usage }}%</div>
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                {% else %}
                    <tr>
                        <td colspan="5" class="text-center">暂无数据</td>
                    </tr>
                {% endif %}
            </tbody>
        </table>
    </div>
</div>

<!-- 最近告警信息 -->
<div class="card mt-4">
    <div class="card-header">
        <h5 class="mb-0">最近告警信息</h5>
    </div>
    <div class="card-body">
        <table class="table">
            <thead>
                <tr>
                    <th>时间</th>
                    <th>主机</th>
                    <th>级别</th>
                    <th>描述</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% if recent_alerts %}
                    {% for alert in recent_alerts %}
                    <tr>
                        <td>{{ alert.created_at|date:"Y-m-d H:i:s" }}</td>
                        <td>{{ alert.host.hostname }}</td>
                        <td>
                            <span class="badge {% if alert.level == '严重' %}bg-danger
                                {% elif alert.level == '紧急' %}bg-warning text-dark
                                {% elif alert.level == '告警' %}bg-primary
                                {% else %}bg-secondary{% endif %}">
                                {{ alert.level }}
                            </span>
                        </td>
                        <td>{{ alert.description }}</td>
                        <td>
                            <button class="btn btn-sm btn-success" data-alert-id="{{ alert.id }}">已确认</button>
                            <button class="btn btn-sm btn-secondary" data-alert-id="{{ alert.id }}">已忽略</button>
                        </td>
                    </tr>
                    {% endfor %}
                {% else %}
                    <tr>
                        <td colspan="5" class="text-center">暂无告警信息</td>
                    </tr>
                {% endif %}
            </tbody>
        </table>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const csrftoken = getCookie('csrftoken');
        
        // 优化事件委托，将事件监听器添加到表格容器
        document.querySelector('.table').addEventListener('click', function(e) {
            const target = e.target;
            if (target.classList.contains('btn')) {
                const alertId = target.dataset.alertId;
                if (target.classList.contains('btn-success')) {
                    confirmAlert(alertId);
                } else if (target.classList.contains('btn-secondary')) {
                    ignoreAlert(alertId);
                }
            }
        });

        // 获取CSRF令牌
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        // 处理告警状态的通用函数
        async function handleAlert(alertId, action) {
            try {
                const response = await fetch(`/alert/${alertId}/${action}/`, {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': csrftoken,
                        'Content-Type': 'application/json',
                    },
                });

                if (response.ok) {
                    // 局部刷新而不是整页刷新
                    const data = await response.json();
                    updateAlertTable(data);
                } else {
                    throw new Error('请求失败');
                }
            } catch (error) {
                console.error('处理告警时出错:', error);
                alert('操作失败，请重试');
            }
        }

        // 确认告警
        async function confirmAlert(alertId) {
            if (confirm('确定要将此告警标记为已确认吗？')) {
                await handleAlert(alertId, 'confirm');
            }
        }

        // 忽略告警
        async function ignoreAlert(alertId) {
            if (confirm('确定要将此告警标记为已忽略吗？')) {
                await handleAlert(alertId, 'ignore');
            }
        }
    });
</script>
{% endblock %} 